package cn.rwklyd.BookKeeping.controller;

import cn.rwklyd.BookKeeping.constant.MessageConstant;
import cn.rwklyd.BookKeeping.mapper.mybatisPlus.AdminMapper_Mp;
import cn.rwklyd.BookKeeping.pojo.Result;
import cn.rwklyd.BookKeeping.pojo.User;
import cn.rwklyd.BookKeeping.pojo.vo.LoginUser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/user")
@Tag(name = "用户管理", description = "用户增删查改接口")
public class UserController {

    @Autowired
    private AdminMapper_Mp adminMapper_mp;

    /**
     * 获取当前用户信息
     */
    @GetMapping("/getUserInfo")
    @Operation(summary = "获取当前用户信息", description = "从安全上下文中获取当前登录用户的信息")
    public Result<User> getUserInfo() {
        // 从SecurityContextHolder中获取当前登录用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof LoginUser) {
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            User currentUser = loginUser.getUser();

            // 获取用户ID
            Integer userId = currentUser.getId();
            log.info("获取当前用户信息，用户ID: {}", userId);

            // 从数据库中查询完整的用户信息
            User userInfo = adminMapper_mp.selectById(userId);

            if (userInfo != null) {
                // 出于安全考虑，清除密码信息
                userInfo.setPassword(null);
                return Result.success(userInfo);
            } else {
                return Result.error("未找到用户信息");
            }
        }

        return Result.error(MessageConstant.USER_NOT_LOGIN);
    }

    /**
     * 用户修改个人信息
     */
    @PutMapping("/updateUserInfo")
    @PreAuthorize("hasAuthority('view_users')")
    @Operation(summary = "用户修改跟人信息", description = "用户修改跟人信息")
    public Result<String> updateUserInfo(@RequestBody User user) {
        // 先检查邮箱是否已被其他用户使用
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, user.getEmail())
                .ne(User::getId, user.getId()); // 排除当前用户

        // 查询是否存在相同邮箱的其他用户
        Long count = adminMapper_mp.selectCount(queryWrapper);

        if (count > 0) {
            // 存在相同邮箱的其他用户，返回错误信息
            return Result.error(MessageConstant.EMAIL_ALREADY_EXISTS);
        }

        // 邮箱验证通过，执行更新操作
        adminMapper_mp.updateById(user);
        return Result.success(MessageConstant.SUCCESS);
    }

    // 修改用户密码
    @PutMapping("/updateUserPassword")
    @PreAuthorize("hasAuthority('view_users')")
    @Operation(summary = "修改用户密码", description = "修改用户密码")
    public Result<String> updateUserPassword(@RequestBody Map<String, Object> passwordData) {
        Integer userId = null;
        // 从上下文中获取当前用户ID
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof LoginUser) {
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            User currentUser = loginUser.getUser();
            userId = currentUser.getId();
        }

        String oldPassword = (String) passwordData.get("oldPassword");
        String newPassword = (String) passwordData.get("newPassword");

        // 参数校验
        if (userId == null || oldPassword == null || newPassword == null) {
            return Result.error(MessageConstant.PARAM_ERROR);
        }

        // 根据用户ID查询用户
        User user = adminMapper_mp.selectById(userId);
        if (user == null) {
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        // 创建密码编码器
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        // 验证旧密码是否正确
        if (!passwordEncoder.matches(oldPassword, user.getPassword())) {
            return Result.error("旧密码不正确");
        }

        // 检查新密码是否与旧密码相同
        if (passwordEncoder.matches(newPassword, user.getPassword())) {
            return Result.success(MessageConstant.PASSWORD_SAME);
        }

        // 对新密码进行加密
        String encodedPassword = passwordEncoder.encode(newPassword);

        // 更新用户密码
        User updateUser = new User();
        updateUser.setId(userId);
        updateUser.setPassword(encodedPassword);
//        updateUser.setUpdatedAt(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
//
        // 执行更新操作
        int result = adminMapper_mp.updateById(updateUser);

        if (result > 0) {
            return Result.success(MessageConstant.SUCCESS);
        } else {
            return Result.error(MessageConstant.FAILED);
        }
    }

    /**
     * 验证用户密码是否正确
     */
    @PostMapping("/verifyPassword")
    @PreAuthorize("hasAuthority('view_users')")
    @Operation(summary = "验证用户密码", description = "验证用户当前密码是否正确")
    public Result<Boolean> verifyPassword(@RequestBody Map<String, Object> passwordData) {
        log.info("验证用户密码");
        
        // 从请求体中获取必要信息
        Integer userId = (Integer) passwordData.get("userId");
        String password = (String) passwordData.get("password");
        
        // 参数校验
        if (userId == null || password == null) {
            return Result.error(MessageConstant.PARAM_ERROR);
        }
        
        // 根据用户ID查询用户
        User user = adminMapper_mp.selectById(userId);
        if (user == null) {
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        
        // 创建密码编码器
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        
        // 验证密码是否正确
        boolean isMatch = passwordEncoder.matches(password, user.getPassword());
        
        if (isMatch) {
            return Result.success(true);
        } else {
            return Result.error("密码不正确");
        }
    }
}
